package customerEnter.Frame.ehcache.AvailableEhcache;

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;
import customerEnter.Frame.ehcache.major.EcacheDataParameter;
import customerEnter.Frame.ehcache.major.EcacheFactory;

/**
 * 緩存數據封裝
 * 
 * 类名称：EcacheDataTransmission 类描述： 创建人：dy 创建时间：2016-3-29 上午11:15:47
 * 
 */
@SuppressWarnings({ "unchecked" })
public class EcacheDataTransmission {
	/**
	 * 初始化緩存 创建一个新的实例 EcacheDataTransmission.
	 * 
	 */
	private EcacheDataParameter	ecacheDataParameter	= new EcacheDataParameter();

	private EcacheDataTransmission() {
		ecacheDataParameter.setEach(EcacheFactory.EhcacheState());
	}

	public static EcacheDataTransmission getEcacheDataTransmission() {
		return new EcacheDataTransmission();
	}

	/**
	 * 取出 Element類型
	 */
	public Element getElementEach(Object key) {
		return ecacheDataParameter.getEach().get(key);
	}

	/**
	 * 取出 对象類型 对象要实现序列化
	 */
	@SuppressWarnings("deprecation")
	public <T> T getObjectEach(Object key) {
		Object object = null;
		try {
			object = ecacheDataParameter.getEach().get(key).getValue();
		} catch (Exception e) {
			object = null;
		}
		return (T) object;
	}

	/**
	 * 取出jsonarray 不用序列化
	 */
	public JSONArray getJsonArray(Object key) {
		JSONArray jsonArray = null;
		try {
			jsonArray = (JSONArray) getEcacheDataTransmission().getElementEach(key).getObjectValue();
		} catch (Exception e) {
			jsonArray = new JSONArray();
		}
		return jsonArray;
	}

	/**
	 * 取出list類型
	 */
	@SuppressWarnings("deprecation")
	public List<?> getListEach(Object key) {
		Element element = ecacheDataParameter.getEach().get(key);
		List<Object> list = new ArrayList<Object>();
		try {
			list = (List<Object>) element.getValue();
		} catch (Exception e) {
			System.out.println("沒有這個key 要加入緩存");
		}
		return list;
	}

	public Cache GetEach() {
		return ecacheDataParameter.getEach();
	}

	/**
	 * 銷毀緩存
	 */
	public void doStory() {
		getEcacheDataTransmission().ecacheDataParameter.getEach().flush();
	}

}
